<template>
  <div class="user-favorite-page">
    <div class="favorites-container">
      <div class="favorites-header">
        <h3>我的收藏题目</h3>
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索收藏的题目..."
            @input="handleSearch"
            :prefix-icon="Search"
          />
        </div>
      </div>

      <!-- 收藏列表内容区域 -->
      <div class="favorites-content">
        <!-- 加载状态 -->
        <div v-if="favoritesLoading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>

        <!-- 收藏列表 -->
        <div class="favorites-list" v-else-if="favoriteQuestions.length > 0">
          <div
            v-for="question in favoriteQuestions"
            :key="question.questionId"
            class="favorite-item"
            @click="goToQuestion(question.questionId)"
          >
            <div class="question-info">
              <h4 class="question-title">{{ question.title }}</h4>
              <div class="question-meta">
                <el-tag :type="getDifficultyType(question.difficulty)" size="small">
                  {{ getDifficultyText(question.difficulty) }}
                </el-tag>
                <span class="favorite-time" v-if="question.createTime">
                  收藏于 {{ formatTime(question.createTime) }}
                </span>
              </div>
            </div>
            <div class="question-actions">
              <el-button
                type="text"
                size="small"
                @click.stop="removeFavorite(question.questionId)"
                class="remove-btn"
              >
                取消收藏
              </el-button>
            </div>
          </div>

          <!-- 加载更多按钮 -->
          <div class="load-more-container" v-if="hasMore">
            <div v-if="loadingMore" class="loading-more">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
            <div v-else class="load-more-trigger">
              <el-button type="primary" @click="loadMore">加载更多</el-button>
            </div>
          </div>

          <!-- 没有更多数据 -->
          <div v-else-if="favoriteQuestions.length > 0" class="no-more-data">
            <span>没有更多题目了</span>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无收藏题目">
            <el-button type="primary" @click="$router.push('/home/question')">
              去收藏题目
            </el-button>
          </el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getFavoriteListService, toggleFavoriteService } from '@/apis/favorite'
import { Loading, Search } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ZlMessage } from '@/utils/message'

const favoriteQuestions = ref([])

// 收藏相关状态
const favoritesLoading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const favoritesTotal = ref(0)
const loadingMore = ref(false)
const hasMore = ref(true)

// 获取收藏列表
async function getFavoriteList(isLoadMore = false) {
  try {
    if (isLoadMore) {
      loadingMore.value = true
    } else {
      favoritesLoading.value = true
      currentPage.value = 1
      favoriteQuestions.value = []
      hasMore.value = true
    }

    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }

    // 如果有搜索关键词，添加到参数中
    if (searchKeyword.value.trim()) {
      params.keyword = searchKeyword.value.trim()
    }

    const res = await getFavoriteListService(params)
    console.log('收藏列表响应:', res)

    let newQuestions = []
    let total = 0

    // 根据后端返回的数据结构处理
    if (res.rows) {
      newQuestions = res.rows || []
      total = res.total || 0
    } else if (res.data) {
      newQuestions = res.data || []
      total = res.total || 0
    }

    if (isLoadMore) {
      // 加载更多时追加数据
      favoriteQuestions.value = [...favoriteQuestions.value, ...newQuestions]
    } else {
      // 首次加载或搜索时替换数据
      favoriteQuestions.value = newQuestions
    }

    favoritesTotal.value = total

    // 判断是否还有更多数据
    hasMore.value = favoriteQuestions.value.length < total
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    if (!isLoadMore) {
      favoriteQuestions.value = []
      favoritesTotal.value = 0
    }
    ZlMessage.error('获取收藏列表失败')
  } finally {
    favoritesLoading.value = false
    loadingMore.value = false
  }
}

// 跳转到答题页面（新页面打开）
function goToQuestion(questionId) {
  window.open(`/anwser?questionId=${questionId}`, '_blank')
}

// 取消收藏
async function removeFavorite(questionId) {
  try {
    await toggleFavoriteService(questionId)
    ZlMessage.success('已取消收藏')
    // 重新获取收藏列表
    await getFavoriteList()
  } catch (error) {
    console.error('取消收藏失败:', error)
    ZlMessage.error('取消收藏失败')
  }
}

// 获取难度类型
function getDifficultyType(difficulty) {
  switch (difficulty) {
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取难度文本
function getDifficultyText(difficulty) {
  switch (difficulty) {
    case 1:
      return '简单'
    case 2:
      return '中等'
    case 3:
      return '困难'
    default:
      return '未知'
  }
}

// 搜索处理
function handleSearch() {
  getFavoriteList() // 搜索时重置到第一页
}

// 加载更多
function loadMore() {
  if (hasMore.value && !loadingMore.value) {
    currentPage.value++
    getFavoriteList(true)
  }
}

// 格式化时间
function formatTime(timeStr) {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  getFavoriteList()
})
</script>

<style lang="scss" scoped>
.user-favorite-page {
  .favorites-container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .favorites-header {
      padding: 20px 24px;
      border-bottom: 1px solid #e0e0e0;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        font-size: 18px;
        font-weight: 600;
        color: #222;
        margin: 0;
      }

      .search-box {
        width: 300px;

        .el-input {
          .el-input__wrapper {
            border-radius: 20px;
            border: 1px solid #dcdfe6;

            &:hover {
              border-color: #c0c4cc;
            }

            &:focus-within {
              border-color: #409eff;
            }
          }
        }
      }
    }

    .favorites-content {
      padding: 20px 24px;

      .loading-container {
        padding: 24px;
      }

      .favorites-list {
        .favorite-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px 20px;
          background: #f8f9fa;
          border: 1px solid #e0e0e0;
          border-radius: 8px;
          margin-bottom: 12px;
          cursor: pointer;
          transition: all 0.3s ease;
          position: relative;

          &:hover {
            border-color: #409eff;
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
            background: white;

            .question-actions {
              opacity: 1;
              visibility: visible;
            }
          }

          .question-info {
            flex: 1;

            .question-title {
              font-size: 16px;
              font-weight: 500;
              color: #222;
              margin: 0 0 8px 0;
              line-height: 1.4;
            }

            .question-meta {
              display: flex;
              align-items: center;
              gap: 12px;

              .favorite-time {
                font-size: 12px;
                color: #999;
              }
            }
          }

          .question-actions {
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;

            .remove-btn {
              color: #f56c6c;
              font-size: 12px;
              padding: 4px 8px;

              &:hover {
                color: #f56c6c;
                background-color: #fef0f0;
              }
            }
          }
        }

        .load-more-container {
          display: flex;
          justify-content: center;
          padding: 20px 0;
          border-top: 1px solid #e0e0e0;
          margin-top: 20px;

          .loading-more {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #666;
            font-size: 14px;

            .el-icon {
              font-size: 16px;
            }
          }

          .load-more-trigger {
            .el-button {
              padding: 8px 24px;
              border-radius: 20px;
              font-size: 14px;
              font-weight: 500;

              &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
              }
            }
          }
        }

        .no-more-data {
          display: flex;
          justify-content: center;
          padding: 20px 0;
          color: #999;
          font-size: 14px;
        }
      }

      .empty-state {
        padding: 40px 24px;
        text-align: center;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .user-favorite-page .favorites-container .favorites-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;

    .search-box {
      width: 100%;
    }
  }
}
</style>

